package edu.cs346.group5.ui.forumpages;

import java.awt.BorderLayout;
import javax.swing.JOptionPane;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Image;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.JLabel;
import net.miginfocom.swing.MigLayout;
import javax.swing.BoxLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Date;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.ImageIcon;
import javax.swing.LayoutStyle.ComponentPlacement;

import edu.cs346.group5.datastores.Comment;
import edu.cs346.group5.datastores.Topic;
import edu.cs346.group5.logic.AddViewTopic;
import edu.cs346.group5.logic.Home;
import edu.cs346.group5.logic.Login;
import edu.cs346.group5.logic.Profile;
import edu.cs346.group5.logic.ViewTopic;
import edu.cs346.group5.ui.ButtonColumn;
import edu.cs346.group5.ui.MenuFactory;
import edu.cs346.group5.ui.StarRater;
import edu.cs346.group5.ui.userpages.home;
import edu.cs346.group5.ui.userpages.user_page.ListItem;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.SwingConstants;
import javax.swing.JTable;

public class view_topic extends JFrame {

	private JPanel contentPane;
	private Object[][] commentTableObjects;
	final JTable table;

	/**
	 * Launch the application.
	 */


	/**
	 * Create the frame.
	 */
	public view_topic(final Topic topic) {
		setTitle("View Topic");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 600, 681);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		
		setJMenuBar(MenuFactory.getMenu(this));
		
		Image image = null;
		try {
		    URL url = new URL(topic.getImageUrl().trim());
		    image = ImageIO.read(url);
		} catch (IOException e) {
			URL url;
			try {
				url = new URL("http://images2.wikia.nocookie.net/__cb20090329133961/superfriends/images/a/a5/No_Photo_Available.jpg");
				image = ImageIO.read(url);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}

		JLabel imageLable = new JLabel(new ImageIcon(image.getScaledInstance(-1, 150, java.awt.Image.SCALE_SMOOTH)));
		imageLable.setBounds(15, 16, 0, 0);
		contentPane.setLayout(null);
		contentPane.add(imageLable);
		
		JLabel lblComment = new JLabel("Comment:");
		lblComment.setBounds(15, 229, 64, 14);
		contentPane.add(lblComment);
		
		final JTextArea textAreaComment = new JTextArea();
		textAreaComment.setBounds(79, 229, 495, 69);
		contentPane.add(textAreaComment);
		
		JButton btnAddComment = new JButton("Add Comment");
		btnAddComment.setBounds(439, 309, 135, 23);
		contentPane.add(btnAddComment);
		btnAddComment.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e)
					{
						java.util.Date today = new java.util.Date();
						java.sql.Date sqlToday = new java.sql.Date(today.getTime());
						Comment comment = new Comment();
						comment.setPostedBy(Login.LoggedInUser.Email);
						comment.setPostDate(sqlToday);
						comment.setContent(textAreaComment.getText());
						comment.setPostedById(Login.LoggedInUser.Id);
						comment.setInReplyTo(topic.getItemId());
						ViewTopic.InsertComment(comment);
						textAreaComment.setText("");
						DefaultTableModel model = (DefaultTableModel) table.getModel();
						model.addRow(new Object[]{sqlToday.toString(), Login.LoggedInUser.FirstName + " " + Login.LoggedInUser.LastName, comment.getContent()});
					}
				});
		StarRater overallStarRater = new StarRater(5, (topic.getTotalPoints() == 0? 1 : topic.getTotalPoints()) / (topic.getNumberOfVotes() == 0? 1 : topic.getNumberOfVotes()), 0);
		overallStarRater.setBounds(50, 180, 150, 30);
		overallStarRater.disable();
		contentPane.add(overallStarRater);
		
		final StarRater userStarRater = new StarRater(5, 0, 0);
		userStarRater.setBounds(369, 180, 150, 30);
		userStarRater.addStarListener(
	            new StarRater.StarListener()   {
	                public void handleSelection(int selection) {
	                    ViewTopic.InsertRating(selection, topic.getPostId());
	                    userStarRater.disable();
	                }
	            });
		contentPane.add(userStarRater);
		
		JLabel lblTopicPicture = new JLabel(new ImageIcon(image.getScaledInstance(-1, 150, java.awt.Image.SCALE_SMOOTH)));
		lblTopicPicture.setBounds(15, 16, 151, 135);
		contentPane.add(lblTopicPicture);
		
		JLabel lblTopicName = new JLabel("");
		lblTopicName.setHorizontalAlignment(SwingConstants.CENTER);
		lblTopicName.setBounds(155, 16, 419, 14);
		contentPane.add(lblTopicName);
		lblTopicName.setText(topic.getTopicName());
		
		JLabel lblDescriptions = new JLabel("Description:");
		lblDescriptions.setBounds(176, 42, 72, 14);
		contentPane.add(lblDescriptions);
		
		JLabel lblDescription = new JLabel("New label");
		lblDescription.setVerticalAlignment(SwingConstants.TOP);
		lblDescription.setBounds(252, 42, 322, 109);
		contentPane.add(lblDescription);
		lblDescription.setAutoscrolls(true);
		lblDescription.setText("<html><div style='width:250px'>" +topic.getDescription()+ "</div></html>");
		
		JLabel lblTopicsRating = new JLabel("Topics Rating");
		lblTopicsRating.setBounds(52, 164, 99, 14);
		contentPane.add(lblTopicsRating);
		
		JLabel lblRateThisTopic = new JLabel("Rate This Topic!");
		lblRateThisTopic.setBounds(369, 162, 99, 14);
		contentPane.add(lblRateThisTopic);
		
		String[] columnNames = {"Date","Posted By","Comment"};
		Comment[] comments = ViewTopic.GetTopicComments(topic.getItemId());
		commentTableObjects = new Object[comments.length][3];
		for(int i = 0; i < comments.length; i++){
			commentTableObjects[i][0] = (Object)comments[i].getPostDate().toString();
			commentTableObjects[i][1] = (Object)comments[i].getPostedBy();
			commentTableObjects[i][2] = (Object)comments[i].getContent();
		}
		Object[] p = {"we", "sd", "er"};
		TableModel model = new DefaultTableModel(commentTableObjects, columnNames);
		table = new JTable(model);
		table.addMouseListener(new MouseAdapter() {
			public void mouseClicked(MouseEvent e) {
				JTable target = (JTable)e.getSource();
			    int row = target.getSelectedRow();
			    int column = target.getSelectedColumn();
			    String comment = target.getValueAt(row, 2).toString();
			    if(Login.LoggedInUser.isAdmin){
			    	String[] choices = {"Close" , "Delete Comment"};
			    	int response = JOptionPane.showOptionDialog(null
			    			, "<html><div style='width:250px'>" +comment + "</div></html>"
                            , target.getValueAt(row, 0).toString() + " - " + target.getValueAt(row, 1).toString()
                            , JOptionPane.YES_NO_OPTION
                            , JOptionPane.PLAIN_MESSAGE
                            , null
                            , choices
                            , "None of your business");
			    	switch (response) {
	                case 0: 
	                	
	                    break;
	                case 1:
	                	DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
	    			    java.util.Date date = null;
	    				try {
	    					date = formatter.parse(target.getValueAt(row, 0).toString());
	    				} catch (ParseException e1) {
	    					// TODO Auto-generated catch block
	    					e1.printStackTrace();
	    				}
	    				Date sqlDate = new Date(date.getTime());
	                    ViewTopic.DeleteTopic(comment, sqlDate);
	                    ((DefaultTableModel)table.getModel()).removeRow(table.getSelectedRow());
	                    break;
	                case -1:
	                    //... Both the quit button (3) and the close box(-1) handled here.
	                    System.exit(0);     // It would be better to exit loop, but...
	                default:
	                    //... If we get here, something is wrong.  Defensive programming.
	                    JOptionPane.showMessageDialog(null, "Unexpected response " + response);
	            }
			    }
			    else{
			    JOptionPane.showMessageDialog(null, "<html><div style='width:250px'>" + comment + "</div></html>", target.getValueAt(row, 0).toString() + " - " + target.getValueAt(row, 1).toString(), JOptionPane.PLAIN_MESSAGE);
			    }
		    }
		});
		table.getColumn("Date").setMaxWidth(75);
		table.getColumn("Posted By").setMaxWidth(200);
		JScrollPane pane = new JScrollPane(table);
		pane.setBounds(10, 338, 564, 279);
		contentPane.add(pane);
		
		JButton btnAddToWish = new JButton("Add to wish list");
		btnAddToWish.setBounds(313, 309, 119, 23);
		contentPane.add(btnAddToWish);
		btnAddToWish.addActionListener(
				new ActionListener(){
					public void actionPerformed(ActionEvent e)
					{
						ViewTopic.AddToWishList(Login.LoggedInUser.Id, topic.getItemId());
					}
				});
		
		if(Login.LoggedInUser.isAdmin){
			JButton btnDeleteTopic = new JButton("Delete this topic");
			btnDeleteTopic.setBounds(11, 309, 140, 23);
			contentPane.add(btnDeleteTopic);
			btnDeleteTopic.addActionListener(
					new ActionListener(){
						public void actionPerformed(ActionEvent e)
						{
							ViewTopic.DeleteTopic(topic.getItemId(), topic.getPostId());
							home x = new home();
							x.setVisible(true);
							dispose();
						}
					});
		}
		
	}
}
